package com.kungfuhacking.wristbandpro.base.presenter;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.alibaba.fastjson.JSONObject;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.bean.UploadBean;
import com.kungfuhacking.wristbandpro.base.view.BaseView;
import com.kungfuhacking.wristbandpro.base.view.TakePhotoView;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import java.io.File;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Aaron on 17/5/12.
 */

public class PhotoPresenter implements BasePresenter {

    /*相册选择的code*/
    public static final int PHOTO_ALBUM_CODE = 1041;
    /*拍照的code*/
    public static final int TAKE_PHOTO_CODE = 1042;
    /* 裁剪*/
    public static final int PHOTO_RESOULT = 1043;

    private File currentFile;
    private Intent mIntent;

    public File getCurrentFile() {
        return currentFile;
    }

    /**
     * 拍照
     *
     * @param requestCode
     * @param view
     */
    public void getTakePhoto(int requestCode, BaseView view) {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + Constant.PHOTO_PATH;
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");
//        return Uri.fromFile(currentFile);
        mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        view.nextActivityForPhoto(mIntent, requestCode);
    }

    /**
     * 相册选择的图片
     *
     * @param data
     */
    public Uri checkSelectPhoto(Intent data, TakePhotoView view) {

        if (data == null) {
            view.showErr("图片读取失败");
            return null;
        }

        Uri selectedImage = data.getData();
        if (selectedImage == null) {
            view.showErr("图片读取失败");
            return null;
        }

        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = view.getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        if (cursor == null) {
            view.showErr("图片读取失败");
            return null;
        }
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return Uri.fromFile(new File(picturePath));

    }

    /**
     * 从相册中选择照片
     *
     * @param view
     */
    public void getFromPhotoAlbum(int requestCode, BaseView view) {
        mIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        view.nextActivityForPhoto(mIntent, requestCode);
    }

    /**
     * 获取七牛上传的tiken
     *
     * @param bytes
     */
    protected void getUploadToken(final byte[] bytes, final BaseView view, final OnResultListener resultListener) {

        JSONObject j = new JSONObject();
        j.put("token", view.getToken());

        RetrofitHttpUtil
                .getInstance()
                .uploadQiNiuToken(
                        new Observer<UploadBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                compositeDisposable.add(d);
                                view.showLoading("获取中...");
                            }

                            @Override
                            public void onNext(UploadBean uploadBean) {
                                view.hideLoading();
                                if (uploadBean.getCode() == 0)
                                    upLoadPic(uploadBean, bytes, view, resultListener);//根据token上传图片
                                else
                                    view.showErr(uploadBean.getCode_msg());
                            }

                            @Override
                            public void onError(Throwable e) {
                                view.hideLoading();
                                view.showErr("网络错误 : " + e.getMessage());
                            }

                            @Override
                            public void onComplete() {
                            }
                        }
                        , new RequestBean().setData(j.toString()));
    }

    /**
     * 上传图片
     *
     * @param uploadBean
     * @param bytes
     */
    protected void upLoadPic(final UploadBean uploadBean, byte[] bytes, final BaseView view, final OnResultListener resultListener) {

        view.showLoading("上传中...");
        UploadManager uploadManager = new UploadManager();
        uploadManager.put(bytes, uploadBean.getPath(), uploadBean.getToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String s, ResponseInfo responseInfo, org.json.JSONObject jsonObject) {

                        view.hideLoading();

                        if (responseInfo.isOK() && resultListener != null) {

                            resultListener.onSuccess(uploadBean.getDomain() + uploadBean.getPath());

//                            imageUrl = uploadBean.getDomain() + uploadBean.getPath();
//                            ipersonalInfoView.setImg(imageUrl);
//                            upDateUserInfo();

                        } else
                            view.showErr("图片上传失败");

                    }

                }, null);

    }

    public abstract class OnResultListener {
        public abstract void onSuccess(String imgUrl);
    }

    public OnResultListener onResultListener;

    @Override
    public void clearRequest() {
        compositeDisposable.clear();
    }
}
